﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.RegularExpressions;

namespace Neoit.Utils
{
    /// <summary>
    /// HttpHelper
    /// </summary>
    public static class HttpHelper
    {


        // 参数处理类

        #region methond 字符串转 System.Net.Http.HttpMethod、ignorecase
#nullable enable
        /// <summary>
        /// methond 字符串转 System.Net.Http.HttpMethod、ignorecase
        /// </summary>
        /// <param name="httpMethodString"></param>
        /// <returns></returns>
        public static HttpMethod? ConvertToHttpMethod(string httpMethodString)
        {
            httpMethodString = httpMethodString.ToLower();
            return httpMethodString switch
            {
                "get" => HttpMethod.Get,
                "post" => HttpMethod.Post,
                "put" => HttpMethod.Put,
                "delete" => HttpMethod.Delete,
                "patch" => HttpMethod.Patch,
                "options" => HttpMethod.Options,
                "head" => HttpMethod.Head,
                "trace" => HttpMethod.Trace,

                _ => null
            };
        }
        #endregion

        #region 解析header键值对字符串（以换行符为分隔）
#nullable enable
        /// <summary>
        /// 解析header键值对字符串（以换行符为分隔）
        /// </summary>
        /// <param name="Headers"></param>
        /// <returns></returns>
        public static Dictionary<string, string> ConvertToHeaderDic(string Headers)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (string.IsNullOrWhiteSpace(Headers)) return dic;
            string[] items = Headers.Split(new string[] { "\r\n", "\r", "\n", }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string pair in items)
            {
                var keyValue = pair.TrimStart();
                var match = Regex.Match(keyValue, "(?!^:):");// 分隔符：第一个且为非首字符的冒号 (?!^:):
                if (match.Success)
                {
                    var key = keyValue.Substring(0, match.Index).Trim();
                    var value = keyValue.Substring(match.Index + 1, keyValue.Length - (match.Index + 1)).TrimStart();
                    dic.Add(key, value);
                }
            }
            return dic;
        }
    }
    #endregion
}
